package com.learning.rocketmq.optimal.throughput;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.io.UnsupportedEncodingException;

/**
 * ClassName: MessageTag
 * Description: 通过Tag 进行过滤
 * Date: 2019/1/14 15:33 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class MessageTag {

    public static void main(String[] args) throws Exception {

//        send();

        consumer();
    }


    public static void send() throws MQClientException, UnsupportedEncodingException, RemotingException, InterruptedException, MQBrokerException {

        // 设置 producerGroup
        DefaultMQProducer producer = new DefaultMQProducer("tag_producer_group");
        // 设置 nameServer
        producer.setNamesrvAddr("10.0.64.106:9876;10.0.64.107:9876");
        producer.start();

        for (int i = 0; i < 50; i++) {
            Message message = new Message();
            message.setTopic("tag_topic");
            // 设置 Tag
            message.setTags("tag_msg");
            message.setBody(("Hello RocketMQ tag_msg > " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));

            SendResult result = producer.send(message);
            System.out.printf("%s%n", result);
        }

        for (int i = 0; i < 50; i++) {
            Message message = new Message();
            message.setTopic("tag_topic");
            // 设置 Tag
            message.setTags("tag_msg_2");
            message.setBody(("Hello RocketMQ tag_msg_2 >  " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));

            SendResult result = producer.send(message);
            System.out.printf("%s%n", result);
        }

        producer.shutdown();
    }

    public static void consumer() throws MQClientException {
        DefaultMQPushConsumer pushConsumer = new DefaultMQPushConsumer("base_consumer_group");
        pushConsumer.setNamesrvAddr("10.0.64.106:9876;10.0.64.107:9876");
        pushConsumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);



        pushConsumer.subscribe("tag_topic", "tag_msg");
        pushConsumer.registerMessageListener((MessageListenerConcurrently) (msgs, context) -> {
            System.out.printf(Thread.currentThread().getName() + "收到新消息：" + msgs + "%n");
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        });

        pushConsumer.start();
    }


}
